package com.liukai.bishe.presenter.userPresenter.impl;

import com.alibaba.fastjson.JSON;
import com.liukai.bishe.model.API;
import com.liukai.bishe.model.doman.user.User;
import com.liukai.bishe.model.doman.user.UserMessage;
import com.liukai.bishe.presenter.userPresenter.IUpdateUserInfoPresenter;
import com.liukai.bishe.utils.RetrofitManager;
import com.liukai.bishe.utils.ToastUtil;
import com.liukai.bishe.view.IBaseCallBack;
import com.liukai.bishe.view.IUpdateUserInfoCallBack;

import java.net.HttpURLConnection;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class IUpdateUserInfoPresenterImpl implements IUpdateUserInfoPresenter {


    private IUpdateUserInfoCallBack mIUpdateUserInfoCallBack;

    @Override
    public void update(User user) {

        String userString = JSON.toJSONString(user);
        ToastUtil.log("IUpdateUserInfoPresenterImpl","userString",userString);
        Retrofit retrofit = RetrofitManager.getInstance().getRetrofit();
        API api = retrofit.create(API.class);
        Call<UserMessage> updateTask = api.update(userString);
        updateTask.enqueue(new Callback<UserMessage>() {
            @Override
            public void onResponse(Call<UserMessage> call, Response<UserMessage> response) {
                int code = response.code();
                ToastUtil.log("IUpdateUserInfoPresenterImpl","修改成功",code+"");
                if(code == HttpURLConnection.HTTP_OK){
                    ToastUtil.log("IUpdateUserInfoPresenterImpl","修改成功",response.body().toString());
                    mIUpdateUserInfoCallBack.result(response.body());
                }
            }

            @Override
            public void onFailure(Call<UserMessage> call, Throwable t) {
                ToastUtil.log("IUpdateUserInfoPresenterImpl","修改失败",t.toString());
            }
        });

    }

    @Override
    public void registerCallback(IBaseCallBack iBaseCallBack) {
        mIUpdateUserInfoCallBack = (IUpdateUserInfoCallBack)iBaseCallBack;
    }

    @Override
    public void unregisterCallback(IBaseCallBack iBaseCallBack) {

        if (mIUpdateUserInfoCallBack != null) {
            mIUpdateUserInfoCallBack = null;
        }

    }
}
